﻿(function(window) {
	var ajax = new _static_ajaxConfig();
	window.static_ajax = ajax;
	window.static_ajax.debug();
	window.static_ajax.ticket("4B1A898D-D864-4D47-950A-17BD5700058D");
})(window);

function _static_ajaxConfig() {
	this.post = function(value) {
		if (value) {
			this._config.url = value;
		}
		this._ajax_config.type = "post";
		return this;
	}
	this.get = function(value) {
		if (value) {
			this._config.url = value;
		}
		this._ajax_config.type = "get";
		return this;
	}
	this.url = function(value) {
		this._config.url = value;
		return this;
	}
	this.arg = function(value) {
		this._config.arg = value;
		return this;
	}
	this.data = function(value) {
		this._ajax_config.data = value;
		return this;
	}
	this.ticket = function(value) {
		this._static.ticket = value;
		return this;
	}
	this.success = function(value) {
		this._ajax_config.success = value;
		return this;
	}
	this.error = function(value) {
		this._ajax_config.error = value;
		return this;
	}	
	this.debug = function() {
		this._static.debug = true;
		return this;
	}
	this.result = function() {
		var url = this._handle_url(this._config.url);
		url = this._handle_arg(url, this._config.arg);

		var config = this._ajax_config;
		config.url = url;

		//将授权ticket赋值
		if (this._static.ticket) {		
			config.data.___ticket=this._static.ticket;
		}

		//复位
		this._rest();

		return config;
	}
	this.ajax = function() {
		var c = this.result();		
		$.ajax(c);
	}
	this._rest = function() {
		this._config = {
			"url": "",
			"arg": ""
		};
		this._ajax_config = {
			"url": "",			
			"type": "post",
			"data": "",
			"dataType": "json",
			"async": true,
			"success": "",
			"error": function(e) {
				alert(e.responseJSON.msg);
			}
		};		
	}
	this._handle_url = function(value) {
		if (!value) {
			return "";
		}

		//首先判断url是不是以斜杆开头，如果是，则去除其开头        
		if (value.substring(0, 1) == "/") {
			value = value.substring(1, value.length);
		}
		//再判断url是不是以斜杆结尾，如果是，则去除结尾
		if (value.substring(value.length - 1, value.length) == "/") {
			value = value.substring(0, value.length - 1);
		}

		if (this._static.debug) {
			value = "Mock" + value;
		}

		value = static_data.pre_api_url + "/" + value;

		return value;
	}
	this._handle_arg = function(url, arg) {
		if (!url) {
			return "";
		}
		if (!arg) {
			return url;
		}
		var allArg = "";
		for (var key in arg) {
			allArg = allArg + key + "=" + arg[key] + "&";
		}
		allArg = allArg.substring(0, allArg.length - 1);

		//如果已经有了参数
		if (url.indexOf("?") != -1) {
			return url + "&" + allArg;
		}

		return url + "?" + allArg;
	}
	this._static = {
		"ticket": "",
		"debug": false
	}
	this._config = {
		"url": "",
		"arg": "",
	}
	this._ajax_config = {
		"url": "",
		"type": "post",
		"data": "",
		"dataType": "json",
		"async": true,
		"success": "",
		"error": function(e) {
			alert(e.responseJSON.msg);
		}
	}
}